package com.cn.pw.frame.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.cn.pw.frame.dao.entity.Role;
import com.cn.pw.frame.dao.entity.User;


public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
	
	@Override
	public User findUserbyName(String name) throws DataAccessException {
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.add(Restrictions.eq("userName", name));
		criteria.setFetchMode("roles", FetchMode.JOIN);
		List findByCriteria = this.getHibernateTemplate().findByCriteria(criteria);
		List<User> users = findByCriteria;
		User user = null;
		if(CollectionUtils.isNotEmpty(users)){
			user = (User)users.get(0);
		}
		
		return user;
	}

	@Override
	public List<User> findUsers(User user) throws DataAccessException {
		/*DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.add(Restrictions.ilike("username",user.getUsername().trim(), MatchMode.START));
		if (StringUtils.isNotBlank(user.getStatus())) {
			criteria.add(Restrictions.eq("status", user.getStatus()));
		}
		return this.getHibernateTemplate().findByCriteria(criteria);*/
		return new ArrayList();
	}

	@Override
	public void saveUser(List<User> users) throws DataAccessException {
		for(User user:users){
			this.getHibernateTemplate().saveOrUpdate(user);
		}
		
	}
	
	public void updateUser(User user) throws DataAccessException{
		this.getHibernateTemplate().saveOrUpdate(user);
	}
	
	@Override
	public Role findRoleByName(String name) throws DataAccessException {
		return (Role)this.getHibernateTemplate().find("from Role where name='"+name+"'").get(0);
	}

	@Override
	public List<User> findAllUsers() throws DataAccessException {
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public User findUserById(Integer id) throws DataAccessException {
		return this.getHibernateTemplate().get(User.class, id);
	}
	
}
